package agent_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStoreUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) StoreUpdateLogic {
	return StoreUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StoreUpdateLogic) StoreUpdate(req *types.StoreBody) error {
	agentId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	storeId := respx.IDParse(req.Id).GetInt64()

	store, err := l.svcCtx.AgentRpc.StoreById(l.ctx, &agentClient.IdBody{Id: storeId})
	if err != nil {
		return err
	}
	if store.Status == 0 {
		return errorx.NewMsgCodeError(errorx.OverBusinessNumber, "审核中，请等待审核结果。")
	}
	// 第一次审核通过之后，不能修改商家名称和营业执照及资质信息
	if store.FirstPass {
		if store.Name != req.Name || store.BusinessLicense != req.Qualifications[0] || store.IndustryLicense != req.Qualifications[1] {
			return errorx.NewMsgCodeError(errorx.CanNotUpdateCode, "第一次审核通过之后，不能再修改商家名称和营业执照及资质信息")
		}
	} else {
		store.Name = req.Name
		store.BusinessLicense = req.Qualifications[0]
		store.IndustryLicense = req.Qualifications[1]
	}

	store.Status = 0
	_, err = l.svcCtx.AgentRpc.StoreUpdate(l.ctx, store)
	if err != nil {
		return err
	}

	reqParam, err := json.Marshal(req)
	if err != nil {
		return err
	}
	_, err = l.svcCtx.AgentRpc.StoreLogAdd(l.ctx, &agentClient.StoreLog{
		StoreId:   storeId,
		Body:      string(reqParam),
		Operation: "update",
		AgentId:   agentId,
	})
	if err != nil {
		return err
	}

	return nil
}
